package com.bjsy.controller;


import com.bjsy.pojo.Book;
import com.bjsy.service.BookService;
import com.bjsy.vo.Result;
import com.bjsy.vo.ResultEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 作者
 * @since 2022-01-19
 */
@RestController
@RequestMapping("/book")
public class BookController {

    //获取业务层对象
    //private BookService bookService = new BookServiceImpl();
    @Autowired
    private BookService bookService;

    /**
     * 获取所有书的信息
     * @return
     */
    @GetMapping
    public Result getAllBook() {
        /*List<Book> bookList = bookService.list();
        return bookList;*/
        /*List<Book> bookList = bookService.list();
        if (!CollectionUtils.isEmpty(bookList)) {
            return Result.success(bookList);
        }
        return Result.fail(10001, "获取失败");*/
        return bookService.getAllBook();
    }

    /**
     * 插入书的信息（新增书）
     * @param book
     * @return
     */
    @PostMapping
    public Result insertBook(@RequestBody Book book) {
        boolean flag = bookService.save(book);
        if (flag) {
            return Result.success(null);
        }
        //return Result.fail(10002, "保存失败");
        return Result.fail(ResultEnum.SAVA_FAIL);
    }

    /**
     * 根据书的id删除
     * @param id
     * @return
     */
    @DeleteMapping("/{id}")
    public Result deleteBook(@PathVariable Integer id) {
        boolean flag = bookService.removeById(id);
        if (flag) {
            return Result.success(null);
        }
        //return Result.fail(10003, "删除失败");
        return Result.fail(ResultEnum.DELETE_FAIL);
    }

    /**
     * 根据id跟新书的信息
     * @param book
     * @return
     */
    @PutMapping
    public Result updateBook(@RequestBody Book book) {
        boolean flag = bookService.updateById(book);
        if (flag) {
            return Result.success(null);
        }
        //return Result.fail(10004, "更新失败");
        return Result.fail(ResultEnum.UPDATE_FAIL);
    }

}

